package com.customization.unionpay.market.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

/**
 * @author sjm
 * @description 个税计提推送待办逻辑
 */
public class SyncIncomeTaxProvisionPushJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncIncomeTaxProvisionPushJob.class);

    @Override
    public void execute() {
        //     1.营销活动事项台账中已入账金额=已核销金额；
        //     2.营销活动事项台账中活动是否核销=是；
        //     3.根据营销活动事项台账查找到最后一笔核销报账单，查询核销报账单中发票类型是否等于“活动交易流水和完税凭证”，是否个税等于是

        try {
            // 营销活动事项台账表单id
            int ledgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            // 营销活动事项台账主表表名
            String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
            log.info("营销活动事项台账主表表名："+ledgerTableName);

            // 核销报账流程id
            int hxbzWorkId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "hxbz_work_id"));
            String workFlowTableName = com.customization.unionpay.market.util.FormDataUtils.getWorkFlowTableName(String.valueOf(hxbzWorkId));
            log.info("核销报账流程表："+workFlowTableName);

            String formId = com.customization.unionpay.market.util.FormDataUtils.getFormIdByWorkFlowId(String.valueOf(hxbzWorkId));
            log.info("核销报账流程表formId："+formId);

            // 查询枚举 活动是否核销
            String selectValueYes =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(ledgerFormId, "hdsfhx", "是");
            log.info("活动是否核销："+selectValueYes);

            // 查询枚举 是否个税计提
            String selectValueIsJi =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(ledgerFormId, "sfgsjt", "否");
            log.info("是否个税计提-否："+selectValueIsJi);

            String selectValueNoJi =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(ledgerFormId, "sfgsjt", "是");
            log.info("是否个税计提-是："+selectValueNoJi);

            String selectValueLiu =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(Integer.valueOf(formId), "fplx", "活动交易流水和完税凭证");
            log.info("活动交易流水和完税凭证："+selectValueLiu);

            String selectValueGe =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(Integer.valueOf(formId), "sfjngs", "是");
            log.info("是否缴纳个税："+selectValueGe);

            String cwsxjsUrl = PropUtils.BB_LOG.getPropValue("marketSubject", "cwsxjs_url");
            log.info("cwsxjsUrl："+cwsxjsUrl);

            // 个税计提流程id
            int workId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "gsjt_work_id"));
            log.info("workId："+workId);
            String isNext = "0";

            if (StrUtil.isNotBlank(selectValueYes)) {
                if (StrUtil.isNotBlank(ledgerTableName)) {
                    RecordSet rs = new RecordSet();
                    StringBuilder sql = new StringBuilder("select  id,yxpthdsqm as actAuthCode,sqr as jbr from ");
                    sql.append(ledgerTableName);
                    sql.append(" where yrzje=yhxje ");
                    sql.append(" and hdsfhx='");
                    sql.append(selectValueYes);
                    sql.append("' and yxpthdsqm is not null and yxpthdsqm <> '' and (sfgsjt = '");
                    sql.append(selectValueIsJi);
                    sql.append("' or sfgsjt is null )");
                    log.info("sql:"+sql.toString());
                    rs.executeQuery(sql.toString());

                    JSONObject mapping = new JSONObject();
                    List<String> ids = new ArrayList<>();
                    while (rs.next()) {
                        String id = Util.null2String(rs.getString("id"));
                        ids.add(id);
                        String jbr = Util.null2String(rs.getString("jbr"));
                        mapping.put(id,jbr);
                    }
                    log.info("ids:"+ids);
                    log.info("mapping:"+mapping);

                    for (String id : ids) {
                        RecordSet rsc = new RecordSet();
                        String jbr = mapping.getString(id);
                        log.info("jbr:"+jbr);

                        User user = new User();
                        user.setUid(Integer.valueOf(jbr));

                        StringBuilder sqlSecond = new StringBuilder("select hxdj,MAX(cjsj) from ");
                        sqlSecond.append(workFlowTableName);
                        sqlSecond.append(" where hxdj='");
                        sqlSecond.append(id);
                        sqlSecond.append("' and fplx='");
                        sqlSecond.append(selectValueLiu);
                        sqlSecond.append("' and sfjngs='");
                        sqlSecond.append(selectValueGe);
                        sqlSecond.append("' group by hxdj ");

                        log.info("sqlSecond:"+sqlSecond.toString());
                        rsc.executeQuery(sqlSecond.toString());

                        while (rsc.next()) {
                            String hxdj = Util.null2String(rsc.getString("hxdj"));
                            log.info("hxdj:"+hxdj);
                            if(!"".equals(hxdj)) {
                                JSONObject json = new JSONObject();
                                JSONObject jbrz = new JSONObject();
                                jbrz.put("name", "sqr");
                                jbrz.put("type", "");
                                jbrz.put("value", jbr);
                                json.put("sqr", jbrz);

                                JSONObject yxsxsqdh = new JSONObject();
                                yxsxsqdh.put("name", "yxsxsqdh");
                                yxsxsqdh.put("type", "");
                                yxsxsqdh.put("value", hxdj);
                                json.put("yxsxsqdh", yxsxsqdh);

                                log.info("size:" + json.size());

                                // 主表字段长度
                                int size = json.size();
                                long time = new Date().getTime();
                                log.info("time:" + time);
                                String requestid = com.customization.unionpay.market.util.FormDataUtils.createWorkFlow(user, json, size, 0, String.valueOf(workId), isNext, "0", "自动发起个税计提流程");
                                log.info("requestid:" + requestid);

                                cwsxjsUrl = cwsxjsUrl.replaceAll("#time#", String.valueOf(time));
                                cwsxjsUrl = cwsxjsUrl.replaceAll("#requestId#", requestid);
                                log.info("cwsxjsUrl:" + cwsxjsUrl);

                                Set<String> users = new HashSet<>();
                                users.add(jbr);
                                FormDataUtils.putWarningMessageInfo(users, "自动发起个税计提流程提醒", "自动发起个税计提流程提醒", cwsxjsUrl, null);
                                log.info("updateIsJiState！");

                                updateIsJiState(hxdj, selectValueNoJi, ledgerTableName);
                            }else {
                                log.info("核销单据为空！");
                            }
                        }
                    }
                } else {
                    log.error("根据营销活动事项台账表单id查询数据库表名失败！");
                }
            } else {
                log.error("hdsfhx枚举为空或找不到！");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }

    /**
     * 修改是否个税计提状态
     * @param id
     * @param value
     * @param tableName
     */
    private void updateIsJiState(String id,String value,String tableName){
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            StringBuilder updateSql = new StringBuilder(" update ");
            updateSql.append(tableName);
            updateSql.append(" set sfgsjt='");
            updateSql.append(value);
            updateSql.append("'  where id ='");
            updateSql.append(id);
            updateSql.append("' ");
            log.info("updateSql:" + updateSql.toString());
            // 修改营销活动事项台账 已使用金额 sum(台账明细*清算金额），已入账金额 sum(明细数据.入账金额），已请款金额 sum(明细数据.请款金额）
            rst.executeUpdate(updateSql.toString());
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
        }
    }
}
